//
//  BIDDateView.m
//  theFifth
//
//  Created by Yeming on 13-6-1.
//
//

#import "BIDDateView.h"
#import "BIDBillsLookoverManager.h"
#import "BIDABill.h"
#import "BIDTypesManager.h"
#import "BIDBillsManager.h"
#import "BIDClockVC.h"
#define kYearLabel  100
#define kMinusButton 101
#define kAddButton 102
#define kSectionheight   40
@interface BIDDateView ()
{
    UIButton *minusYear;
    UILabel *yearlabel;
    UIButton *addYear;
    BIDABill *deleteBill;
    BOOL extended;
    UIView *tableHeadView;
}
@property(strong,nonatomic) NSMutableArray *listOfMonth;
@property(strong,nonatomic) NSMutableArray *extendSection;

@end

@implementation BIDDateView
@synthesize detailMonth,detailYear;
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"%d",detailYear);
   //  [self initViewOfNav];
    extended=NO;
    self.extendSection=[[NSMutableArray alloc] init];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
//    			UIImage *dateimage = [UIImage imageNamed:@"icon0.png"];

}
-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden=NO;
    [self initViewOfNav];
    [self updateDatabase];

}
-(void)initViewOfNav
{
    minusYear=[UIButton buttonWithType:UIButtonTypeCustom];
    minusYear.frame=CGRectMake(70, 8, 30, 30    );
   // minusYear.backgroundColor=[UIColor greenColor];
    minusYear.tag=kMinusButton;
    minusYear.tintColor =[UIColor blackColor];
    [minusYear setTitle:@"－" forState:UIControlStateNormal];
    [minusYear addTarget:self action:@selector(addAndMinusYear:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:minusYear];
    yearlabel=[[UILabel alloc] initWithFrame:CGRectMake(110, 8, 100, 30)];
    yearlabel.text=[NSString stringWithFormat:@"%d",[self getYear]];
    yearlabel.textAlignment=NSTextAlignmentCenter;
    yearlabel.backgroundColor=[UIColor clearColor];
    yearlabel.shadowColor=[UIColor grayColor];
    yearlabel.shadowOffset=CGSizeMake(1, 1);
    [self.navigationController.navigationBar addSubview:yearlabel];
    addYear=[UIButton buttonWithType:UIButtonTypeCustom];
    addYear.showsTouchWhenHighlighted=YES;
    addYear.frame=CGRectMake(220, 8, 30, 30);
    addYear.tag=kAddButton;
    addYear.tintColor=[UIColor blackColor];
    [addYear setTitle:@"+" forState:UIControlStateNormal];

      [addYear addTarget:self action:@selector(addAndMinusYear:) forControlEvents:UIControlEventTouchUpInside];
  //  addYear.backgroundColor=[UIColor redColor];
    [self.navigationController.navigationBar addSubview:addYear];
    
   
    
}
#pragma mark --button events
-(void)addAndMinusYear:(UIButton*)sender
{
    if (sender.tag==kAddButton) {
        NSInteger year=yearlabel.text.integerValue;
        year+=1;
        yearlabel.text=[NSString stringWithFormat:@"%d",year];
       
    }
    else
{
    NSInteger year=yearlabel.text.integerValue;
    year-=1;
    yearlabel.text=[NSString stringWithFormat:@"%d",year];
   }
    [self updateDatabase];
    
    
    self.extendSection=[[NSMutableArray alloc] init];
   // self.listOfMonth=[[NSMutableArray alloc] init];


}
-(void)delete:(id)sender
{
    UIBarButtonItem *bar=sender;
    if (!self.tableView.editing) {
        [bar setTitle:@"Done"];
        self.tableView.editing=YES;
    }
    else
    {
        [bar setTitle:@"Delete"];
        self.tableView.editing=NO;
    }
}


-(NSInteger)getYear
{
    NSDate* now = [NSDate date];
    
    NSCalendar *cal = [NSCalendar currentCalendar];
    
    
    
    
    unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit |NSSecondCalendarUnit ;
    
    NSDateComponents *dd = [cal components:unitFlags fromDate:now];


    NSInteger y = [dd year];
    if (self.detailYear)
    {
         y =self.detailYear;

       }
    return y;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
   
    return self.listOfMonth.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    // Return the number of rows in the section.
    NSInteger rows=0;
    if (self.extendSection.count!=0)
    {
        for (NSNumber *number in self.extendSection)
        {
            NSInteger month=[[self.listOfMonth objectAtIndex:number.integerValue] integerValue];
            if (section==number.integerValue)
            {
              rows=[[BIDBillsLookoverManager shareBillsLookoverManager] billsCountInMonth:month andYear:yearlabel.text.integerValue];
            }
        }
    }
    return rows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    NSMutableArray *bills=nil;
    if (self.extendSection.count!=0)
    {
        for (NSNumber *number in self.extendSection)
        {
            NSInteger month=[[self.listOfMonth objectAtIndex:number.integerValue] integerValue];

            if (indexPath.section ==number.integerValue)
            {
                bills=[[BIDBillsLookoverManager shareBillsLookoverManager] billsArrayInMonth:month andYear:yearlabel.text.integerValue];
            }
        }
    }
    BIDABill *aBill=nil;
    if (bills.count!=0) {
        aBill=[bills objectAtIndex:indexPath.row];
    }
    NSString *typename=nil;
    NSString *subType=nil;
    if (aBill) {
       typename=[[BIDTypesManager shareTypesManager] selectTypeName:aBill.type_ID];
        subType=[[BIDTypesManager shareTypesManager] selectSubTypeName:aBill.subType_ID];
    }
    // Configure the cell...
   NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss "];
    NSDate *date = [dateFormatter dateFromString:aBill.Ctime];
     
    [dateFormatter setDateFormat:@"dd"];
    NSString*timeStr=[dateFormatter stringFromDate:date];


   if (aBill.whichWay==1)
   {
       cell.textLabel.textColor=[UIColor redColor];
}

   else{ cell.textLabel.textColor=[UIColor greenColor];}
    cell.textLabel.text=[NSString stringWithFormat:@"%@--%@ --%@日",typename,subType,timeStr ];
    
    cell.accessoryType=UITableViewCellAccessoryDetailDisclosureButton;
    return cell;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view=[[UIView alloc] init];
     NSInteger number=[[self.listOfMonth objectAtIndex:section] integerValue];

    view.frame=CGRectMake(0, 0, 320, 40);
    view.backgroundColor=[UIColor grayColor];
       UIButton *small=[UIButton buttonWithType:UIButtonTypeCustom];
    small.frame=CGRectMake(60, 0, 150, 30);
    small.tag=section;
    float spend=[[BIDBillsLookoverManager shareBillsLookoverManager] spendAmountCountInMonth:number andYear:yearlabel.text.integerValue];
    float income=[[BIDBillsLookoverManager shareBillsLookoverManager] incomeAmountCountInMonth:number andYear:yearlabel.text.integerValue];
    [small setTitle:[NSString stringWithFormat:@"收入:%.2f",income] forState:UIControlStateNormal];
      [small addTarget:self action:@selector(extendBills:) forControlEvents:UIControlEventTouchUpInside];
     [view addSubview:small];
      
    UILabel *label=[[UILabel alloc] init];
    label.frame=CGRectMake(190, 0, 100, 30);
   // label.sizeToFit
    label.adjustsFontSizeToFitWidth=YES;
    label.backgroundColor=[UIColor clearColor];
    label.textColor=[UIColor redColor];
    label.text=[NSString stringWithFormat:@"消费:%.2f",spend];
    [view addSubview:label];
    [label release];
   
    UILabel *labe=[[UILabel alloc] initWithFrame:CGRectMake(10, 0, 100, 30)];
       labe.text= [NSString stringWithFormat:@"%d 月",number];
    labe.shadowColor=[UIColor grayColor];
    labe.backgroundColor=[UIColor clearColor];
                [view addSubview:labe];
                [labe release];
    //[small release];
    return view;
    [view release];
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return kSectionheight;
}
-(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    BIDClockVC *next=[[BIDClockVC alloc] initWithNibName:@"BIDClockVC" bundle:nil];
    NSInteger month=[[self.listOfMonth objectAtIndex:indexPath.section] integerValue];
    NSMutableArray *array=[[BIDBillsLookoverManager shareBillsLookoverManager] billsArrayInMonth:month andYear:yearlabel.text.integerValue];
    
    BIDABill *bill=[array objectAtIndex:indexPath.row];
    next.aBill=bill;
    [self.navigationController pushViewController:next animated:YES];
}
#pragma mark---section's button
-(void)extendBills:(UIButton*)send
{
    
    NSNumber *number=[NSNumber numberWithInteger:send.tag];
//    extended=YES;
//     [send setTitle:@"合拢" forState:UIControlStateNormal];
     
   
    if ([self.extendSection containsObject:number]) {
        [self.extendSection removeObject:number];
       
    }
    else
    {
        [self.extendSection addObject:number];
        
    }
    
    [self isHadDeleteButton];
   
     [self.tableView reloadData];
    
}
-(void)isHadDeleteButton
{
    if (self.extendSection.count!=0) {
        // extended=YES;
        UIBarButtonItem *bar=[[UIBarButtonItem alloc] initWithTitle:@"删除" style:0 target:self action:@selector(delete:)];
        self.tabBarController.navigationItem.rightBarButtonItem=bar;
        [bar release];
    }
    else
    {
        self.tabBarController.navigationItem.rightBarButtonItem=nil;
    }

}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
  
    
//    NSLog(@"%d---%@",bill.type_ID,[[BIDTypesManager shareTypesManager] selectSubTypeName:bill.subType_ID]);
    
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger month=[[self.listOfMonth objectAtIndex:indexPath.section] integerValue];
    NSMutableArray *array=[[BIDBillsLookoverManager shareBillsLookoverManager] billsArrayInMonth:month andYear:yearlabel.text.integerValue];
    
  deleteBill=[array objectAtIndex:indexPath.row];
    [self alterViewPush];
//   BOOL judge= [[BIDBillsManager shareBillsManager] deleteAPayout:deleteBill];
//    if (judge) {
//        [self updateDatabase];
//    }
//    else
//    {
//        NSLog(@"fails");
//    }

}
-(void)alterViewPush
{
    UIAlertView *alter=[[UIAlertView alloc] initWithTitle:@"提醒" message:@"是否删除" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
   // alter.alertViewStyle
    [alter show];
    [alter release];
    
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (buttonIndex==1)
    {
        BOOL judge= [[BIDBillsManager shareBillsManager] deleteAPayout:deleteBill];
        if (judge) {
            [self updateDatabase];
            deleteBill=nil;
        }
        else
        {
            NSLog(@"fails");
           // self.tableView.editing=YES;
        }

    }
    
}

-(void)updateDatabase
{
    self.listOfMonth=[[BIDBillsLookoverManager shareBillsLookoverManager] arrayOfMonthsInYear:yearlabel.text.integerValue];
    [self.tableView reloadData];
}
-(void)viewWillDisappear:(BOOL)animated
{
    self.tabBarController.navigationItem.rightBarButtonItem=nil;
    [minusYear removeFromSuperview];
    [addYear removeFromSuperview];
    [yearlabel removeFromSuperview];
}
@end
